from api import models
from django.core.validators import RegexValidator
from rest_framework import serializers
from rest_framework.exceptions import ValidationError


class RegisterSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(label='确认密码', style={'input_type': 'password'}, write_only=True)

    class Meta(object):
        model = models.UserInfo
        fields = ['username', 'phone', 'password', 'confirm_password']
        extra_kwargs = {
            'phone': {'validators': [RegexValidator(r'^1[3-9]\d{9}$'), ]},
            'password': {'write_only': True, 'min_length': 8, 'style': {'input_type': 'password'}, }
        }

    def validate_username(self, username):
        exists = models.UserInfo.objects.filter(username=username, deleted=False).exists()
        if exists:
            raise ValidationError('用户名已存在')
        return username

    def validate_phone(self, phone):
        exists = models.UserInfo.objects.filter(phone=phone, deleted=False).exists()
        if exists:
            raise ValidationError("手机号已存在")
        return phone

    def validate_confirm_password(self, confirm_password):
        password = self.initial_data.get('password')
        if password != confirm_password:
            raise ValidationError("两次密码不一致")
        return confirm_password


class AuthSerializer(serializers.Serializer):
    username = serializers.CharField(label='用户名', max_length=32, required=False)
    phone = serializers.CharField(label='手机号', max_length=11, required=False)
    password = serializers.CharField(label='密码', min_length=8, max_length=64, required=True, write_only=True)

    def validate_phone(self, phone):
        username = self.initial_data.get('username')
        if not username and not phone:
            raise ValidationError('用户名或手机为空')
        if username and phone:
            raise ValidationError('用户名或手机只填写一个即可')
        return phone
